package a08_回溯算法;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

/**
 * <p>
 * a08_组合总和2复习3
 * </p>
 *
 * @author flyduck
 * @since 2025/4/9
 */
public class a08_组合总和2复习3 {
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        Arrays.sort(candidates);

        List<List<Integer>> result = new ArrayList<>();
        LinkedList<Integer> path = new LinkedList<>();
        boolean[] used = new boolean[candidates.length];

        traversal(result, path, candidates, target, 0, used, 0);
        return result;
    }

    private void traversal(List<List<Integer>> result,
                           LinkedList<Integer> path,
                           int[] candidates,
                           int target,
                           int sum,
                           boolean[] used,
                           int startIdx){
        if(sum == target){
            result.add(new ArrayList<>(path));
            return;
        }else if(sum > target){
            return;
        }
        for (int i = startIdx; i < candidates.length; i++) {
            if(i > 0 && candidates[i] == candidates[i-1] && !used[i-1]){
                continue;
            }

            path.add(candidates[i]);
            sum += candidates[i];
            used[i] = true;
            traversal(result, path, candidates, target, sum, used, i + 1);
            path.removeLast();
            sum -= candidates[i];
            used[i] = false;
        }
    }
}
